﻿namespace JunFan.Tests.Infrastructure
{
    using System;
    using System.Collections.Generic;
    using Domain;
    using Repositories;

    public static class ItemExtensions
    {
        private static int _currentId;

        public static IEnumerable<Item> Create(this IEnumerable<Item> items, IRepository<Item> repository)
        {
            var createdItems = new List<Item>();

            foreach (var item in items)
            {
                var createdItem = repository.Create(item);
                createdItems.Add(createdItem);
            }
            
            return createdItems;
        }

        public static IEnumerable<Item> Add(this IEnumerable<Item> items)
        {
            return Add(items, new Board());
        }

        public static IEnumerable<Item> Add(this IEnumerable<Item> items, Board board)
        {   
            var addedItems = new List<Item>();

            foreach (var item in items)
            {
                var addedItem = board.AddItem(item);
                addedItems.Add(addedItem);
            }

            return addedItems;
        }

        private static IEnumerable<Item> DoAndReturn(this IEnumerable<Item> items, Func<Item, Item> doit )
        {
            var returnItems = new List<Item>();

            foreach (var item in items)
            {
                var newItem = doit(item);
                
                returnItems.Add(newItem);
            }

            return returnItems;
        }
        
        internal static Item Clone(this Item item)
        {
            var clone = new Item
                {
                    Id = RandomId(),
                    CreatedOn = item.CreatedOn,
                    StartedOn = item.StartedOn,
                    CompletedOn = item.CompletedOn
                };

            return clone;
        }

        private static string RandomId()
        {
            _currentId += 1;

            return string.Format("XYZ{0}", _currentId);
        }
    }
}